clear all;
p = [1.07930195677526e-07,-5.15145556273585e-05,0.00823222900042392,-0.594801372489517,19.6245665325617,-48.2798664701923,1916.48359304268];

x = [0,0,0]';
%初始化输入向量
K = 0.0000001;
kP = 0.02;
kI = 0.006;
kD = 0.0;
%初始化PID的三个参数的学习速率



error_1 = 0;
error_2 = 0;
%记录上一次误差以及上上次误差

learning_mode = 4;
%设置学习规则
ts = 0.001;
%设置迭代周期为1ms
n = 1000;
y = zeros(n,1);
yd = zeros(n,1);
time = zeros(n,1);
w_x1 = zeros(n,1);
w_x2 = zeros(n,1);
w_x3 = zeros(n,1);
w_x1(1) = 0.02;
w_x2(1) = 0.02;
w_x3(1) = 0;
%初始化输入网络的三个权重系数
error = zeros(n,1);
u_1 = 0;
u = zeros(n,1);
u(1) = 0;
wadd = zeros(n,1);
kp = 0.002;
ki = 0.0006;
kd = 0.0;

for k = 1:n
    time(k)=(k-1)*ts;
    %横轴变化
    yd(k) = 10000;
    %输入期望的信号函数-阶跃函数         
    y(k) = polyval(p,u(k));
    %被控对象的离散方程。 x' = Ax + Bu
    
    %计算当前误差
    error(k) = yd(k) - y(k);
    x(1) = error(k) - error_1;
    x(2) = error(k);
    x(3) = error(k) - 2*error_1 + error_2;
    %神经元的输入
    if( k < n )
        u(k+1) = u(k) + kp*x(1) + ki*x(2) + kd*x(3);
        if u(k+1) < 10
            u(k+1) = 0;
        elseif u(k+1) > 80
            u(k+1) = 80;
        end        
    end
%     wadd(k)=abs(w_x1(k))+abs(w_x2(k))+abs(w_x3(k));
%     w11(k) = w_x1(k)/wadd(k);
%     w22(k) = w_x2(k)/wadd(k);
%     w33(k) = w_x3(k)/wadd(k);
%     w=[w11(k),w22(k),w33(k)];
%     %权重系数归一化操作     
%     
%     if( k < n )
%         u(k+1)=u(k)+K*w*x;
%         if u(k+1) < 10
%             u(k+1) = 0;
%         elseif u(k+1) > 80
%             u(k+1) = 80;
%         end
%     end
%     %控制律

    
    %更新神经元输出控制律序列
    if learning_mode == 1
        %无监督的HEBBE学习规则
        w_x1(k+1) = w_x1(k) + kP*u(k)*x(1);
        w_x2(k+1) = w_x2(k) + kI*u(k)*x(2);
        w_x3(k+1) = w_x3(k) + kD*u(k)*x(3);
        K = 1;
        %无监督的HEBBE学习规则
    elseif learning_mode == 2
        %有监督的delta学习规则
        w_x1(k+1) = w_x1(k) + kP*error(k)*x(1);
        w_x2(k+1) = w_x2(k) + kI*error(k)*x(2);
        w_x3(k+1) = w_x3(k) + kD*error(k)*x(3);
        K = 0.12;
        %有监督的delta学习规则
    elseif learning_mode == 3
        %有监督的hebbe学习规则
        w_x1(k+1) = w_x1(k) + kP*error(k)*u(k)*x(1);
        w_x2(k+1) = w_x2(k) + kI*error(k)*u(k)*x(2);
        w_x3(k+1) = w_x3(k) + kD*error(k)*u(k)*x(3);
        K = 0.12;
        %有监督的hebbe学习规则
    elseif learning_mode == 4
        %改进后的有监督的hebbe学习规则
        w_x1(k+1) = w_x1(k) + kP*error(k)*u(k)*(error(k) - error_1);
        w_x2(k+1) = w_x2(k) + kI*error(k)*u(k)*(error(k) - error_1);
        w_x3(k+1) = w_x3(k) + kD*error(k)*u(k)*(error(k) - error_1);
        K = 0.01;
        %改进后的有监督的hebbe学习规则
    end       
    
    error_2 = error_1;
    error_1 = error(k);    
     %更新误差序列    
end


figure(1);
plot(time,yd,'r-',time,y,'b-','linewidth',2);
xlabel('time');ylabel('yd;y');
legend('yd','y');
%打印被控对象跟踪结果
figure(2);
plot(time,u,'r','linewidth',2);
xlabel('time');ylabel('controlinput U');
legend('u');
%打印控制律曲线



